package com.atguigu.flinkWindow;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * 增量聚合函数----改变数据的类型
 * @author wky
 * @create 2021-07-16-19:04
 */
public class AggregateFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        senv.setParallelism(1);
        DataStreamSource<String> streamSource = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<Tuple2<String, Long>> streamOperator = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] split = s.split(" ");
                for (String s1 : split) {
                    collector.collect(Tuple2.of(s1, 1L));
                }
            }
        });
        KeyedStream<Tuple2<String, Long>, Tuple> keyedStream = streamOperator.keyBy(0);
        WindowedStream<Tuple2<String, Long>, Tuple, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));
        //TODO 对窗口内的数据操作  输入输出类型可以不同
        window.aggregate(new org.apache.flink.api.common.functions.AggregateFunction<Tuple2<String, Long>, Long, String>() {
            //创建累加器=》初始化累加器，在窗口创建时调用一次
            @Override
            public Long createAccumulator() {
                Long s = 0L;
                return s;
            }

            //累加过程 每条数据操作一次
            @Override
            public Long add(Tuple2<String, Long> value, Long accumulator) {
                return ++accumulator;
            }

            //获取结果值=》在窗口关闭时触发计算才关闭
            @Override
            public String getResult(Long accumulator) {
                return accumulator.toString() ;
            }

            //合并主要给会话窗口使用的
            @Override
            public Long merge(Long a, Long b) {
                return null;
            }
        }).print();
        senv.execute();
    }
}
